# 导包
import pytest
import time
from datetime import timedelta
from unit_tools.handle_data.yaml_handler import clear_yaml
from unit_tools.other_util.ding_rebot import send_dd_msg
from configs.setting import is_dd_msg
import os

@pytest.fixture(scope="session", autouse=True)
def clear_extract():
    clear_yaml()


def format_duration(seconds):
    return str(timedelta(seconds=seconds)).split('.')[0]

def get_env_from_jenkins(name):
    return os.getenv(name) and os.getenv(name).strip()

def pytest_terminal_summary(terminalreporter, exitstatus, config):
    testcase_total = terminalreporter._numcollected
    passed_num = len(terminalreporter.stats.get('passed', []))
    failed_num = len(terminalreporter.stats.get('failed', []))
    error_num = len(terminalreporter.stats.get('error', []))
    skip_num = len(terminalreporter.stats.get('skipped', []))
    duration = round(time.time() - terminalreporter._sessionstarttime, 2)
    formatted_duration = format_duration(duration)

    pass_rate = f"{(passed_num / testcase_total) * 100:.0f}%" if testcase_total > 0 else "N/A"
    fail_rate = f"{(failed_num / testcase_total) * 100:.0f}%" if testcase_total > 0 else "N/A"
    error_rate = f"{(error_num / testcase_total) * 100:.0f}%" if testcase_total > 0 else "N/A"

    summary = f"""
    自动化测试结果，通知如下，具体执行结果：
    测试用例总数：{testcase_total}  
    测试用例通过数：{passed_num}
    通过率：{pass_rate}
    测试用例失败数：{failed_num}
    失败率：{fail_rate}
    错误数量：{error_num}
    错误率：{error_rate}       
    跳过执行数量：{skip_num}
    执行总时长：{duration}s ({formatted_duration})
    测试项目名称：{ProjectName}
    测试项目构建编号：#{BUILD_NUMBER}
    [构建地址链接]：({BUILD_URL})
    [控制台输出日志链接]：({BUILD_URL + 'console'})
    [Allure测试报告链接]：({BUILD_URL + 'allure'})
    """
    print(summary)
    if is_dd_msg:
        send_dd_msg(summary)